import { getToken } from "../utils";

export function fetchSSE(
    url: string,
    headers: Headers,
    onMessage: (message: string) => void,
    onError?: (error: any) => void
): () => void {
    const worker = new Worker(new URL('./sse-worker.ts', import.meta.url), {
        type: 'module'
    });

    const headersObj: { [key: string]: string } = {};
    headers.forEach((value, key) => {
        headersObj[key] = value;
    });

    const token = getToken();
    if (token) {
        headersObj["Authorization"] = `Bearer: ${token}`;
    }
    headersObj["X-API-Key"] = "4e7kGzY6w9kQpFvL3uXbRzTp8aN5mJw2";

    worker.postMessage({ url, headers: headersObj });

    worker.onmessage = function (event) {
        const { error, message } = event.data;
        if (error) {
            if (onError) {
                onError(message);
            }
        } else {
            onMessage(message);
        }
    };

    // Return a function to close the connection
    return () => {
        worker.postMessage('close');
        worker.terminate(); // Ensure the worker is terminated properly
    };
}
